package com.example;

import java.io.IOException;

import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;


@WebServlet("/setcontext")
public class SetContext extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 从请求url中获取参数
        String name = req.getParameter("name");
        ServletContext context = req.getServletContext();   //获取上下文
        // 根据字符串制作一个JSON对象
        String s = "{\"sites\": [{ \"name\":\"菜鸟教程\" , \"url\":\"www.runoob.com\" }, { \"name\":\"google\" , \"url\":\"www.google.com\" }, { \"name\":\"微博\" , \"url\":\"www.weibo.com\" }]}";
        
        if(name == null){
            name = "null";
        }
        // 设置要共享的变量和值
        context.setAttribute("data",s);      // 将一个对象jsonobj(JSONObject)放入到context的"data"键中

        resp.getWriter().write("<a href = \"/getcontext\">get-context<a>");

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
